package com.example.java_gobang.game;

import com.example.java_gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author hanzishuai
 * @date 2025/03/02 15:41
 * @Description
 */
@Slf4j
@Component
public class Matcher {
    @Autowired
    private OnlineUserManager onlineUserManager;

    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private RoomManger roomManger;

    // 创建三个匹配队列
    private Queue<User> normalQueue = new LinkedList<>();
    private Queue<User> highQueue = new LinkedList<>();
    private Queue<User> veryHighQueue = new LinkedList<>();

    // 把玩家放到队列中
    public void add(User user) {

        if (user.getScore() < 2000) {
            synchronized (normalQueue) {
                normalQueue.offer(user);
                normalQueue.notify();
            }
            log.info("把玩家" + user.getUsername() + "加入到了 normalQueue 中！");
        } else if (user.getScore() >= 2000 && user.getScore() < 3000) {
            synchronized (highQueue) {
                highQueue.offer(user);
                highQueue.notify();
            }
            log.info("把玩家" + user.getUsername() + "加入到了 highQueue 中！");

        } else {
            synchronized (veryHighQueue) {
                veryHighQueue.offer(user);
                veryHighQueue.notify();
            }
            log.info("把玩家" + user.getUsername() + "加入到了 veryHighQueue 中！");
        }
    }

    // 把玩家从匹配队列中删除
    public void remove(User user) {
        if (user.getScore() < 2000) {
            synchronized (normalQueue) {
                normalQueue.remove(user);
            }
            log.info("把玩家" + user.getUsername() + "从 normalQueue 中删除！");
        } else if (user.getScore() >= 2000 && user.getScore() < 3000) {
            synchronized (highQueue) {
                highQueue.remove(user);
            }
            log.info("把玩家" + user.getUsername() + "从 highQueue 中删除！");
        } else {
            synchronized (veryHighQueue) {
                veryHighQueue.remove(user);
            }
            log.info("把玩家" + user.getUsername() + "从 veryHighQueue 中删除！");

        }
    }

    Matcher() {
        Thread t1 = new Thread() {
            public void run() {
                while (true) {
                    handlerMatch(normalQueue);
                }
            }
        };
        t1.start();
        Thread t2 = new Thread() {
            public void run() {
                while (true) {
                    handlerMatch(highQueue);
                }
            }
        };
        t2.start();
        Thread t3 = new Thread() {
            public void run() {
                while (true) {
                    handlerMatch(normalQueue);
                }
            }
        };
        t3.start();
    }

    private void handlerMatch(Queue<User> matchQueue) {
        synchronized (matchQueue) {
            try {
                // 检测队列中人数是否 小于 2
                while (matchQueue.size() < 2) {
                    matchQueue.wait();
                }
                // 从匹配队列中取出两个玩家进行对战
                User player1 = matchQueue.poll();
                User player2 = matchQueue.poll();

                log.info("匹配到两个玩家：" + player1.getUsername() + "," + player2.getUsername());
                WebSocketSession session1 = onlineUserManager.getFromGameHall(player1.getUserId());
                WebSocketSession session2 = onlineUserManager.getFromGameHall(player2.getUserId());

                if (session1 == null) {
                    matchQueue.offer(player2);
                    return;
                }
                if (session2 == null) {
                    matchQueue.offer(player1);
                    return;
                }
                if (player1 == player2) {
                    matchQueue.offer(player1);
                    return;
                }
                // 把玩家放到一个游戏房间中
                Room room = new Room();
                roomManger.add(room, player1.getUserId(), player2.getUserId());
                // 通知两个玩家匹配成功
                MatchResponse matchResponse1 = new MatchResponse();
                matchResponse1.setOk(true);
                matchResponse1.setMessage("matchSuccess");
                String json1 = objectMapper.writeValueAsString(matchResponse1);
                session1.sendMessage(new TextMessage(json1));

                MatchResponse matchResponse2 = new MatchResponse();
                matchResponse2.setOk(true);
                matchResponse2.setMessage("matchSuccess");
                String json2 = objectMapper.writeValueAsString(matchResponse2);
                session2.sendMessage(new TextMessage(json2));
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
